package com.bobo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bobo.auth.common.JWTUtils;
import com.bobo.auth.common.Result;
import com.bobo.domain.SysUser;
import com.bobo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("auth")
public class AuthController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    AuthenticationManager authenticationManager;
   @Autowired
    RedisTemplate redisTemplate;

    /**
     * 产生图形验证码
     * @param uuid
     * @param response
     * @throws IOException
     */
    @RequestMapping("createImageCode")
    public void  createImageCode(String  uuid,HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());//1 给前端一份
        String code = captcha.getCode();//获取产生的验证码
        redisTemplate.opsForValue().set(uuid,code,5, TimeUnit.MINUTES);//2 redis存储一份，有效期5分钟
    }

    /**
     * 根据用户名查询user 用来判断该用户是否已经注册
     * @param username
     * @return
     */
    @RequestMapping("getUserByName")
    public Result getUserByName(String username){
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,username);
        SysUser dbUser = sysUserService.getOne(wrapper);
        return Result.success(dbUser);
    }

    public static final String  salt="123456";//密码盐


    /**
     *
     * @param sysUser
     * @return
     */
    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser){
        //比较验证码输入是否正确
        String code = sysUser.getCode();//用户输入验证码
        String  codeRedis = (String) redisTemplate.opsForValue().get(sysUser.getUuid());
        if(!code.equals(codeRedis)){
            return Result.fail(500,"验证码不正确或已经失效");
        }

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword() + salt);
        authenticationManager.authenticate(authenticationToken);//自动调用UserDetailServiceImpl
        //以上方法如果不抛异常则验证通过.即登录成功
        String token = JWTUtils.createToken(sysUser.getUsername(), 1);
        return Result.success(token);
    }
    /**
     * 用户注册
     * @param sysUser
     * @return
     */
    @RequestMapping("reg")
    public Result reg(@RequestBody SysUser sysUser){
        String s = passwordEncoder.encode(sysUser.getPassword() + salt);//对注册的密码进行加密加盐
        sysUser.setPassword(s);
        boolean b = sysUserService.save(sysUser);
        return b?Result.success():Result.fail();



    }
}
